package com.sskj.level.ui.fragment;


import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.PingCangType;
import com.sskj.level.bean.TradeListBean;
import com.sskj.level.presenter.DealFragmentPresenter;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.mvchelper.RefreshDataSource;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;

@Route(path = RConfig.LEVEL_FRAGMENT_DEAL)//成交
public class DealFragment extends BaseFragment<DealFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R2.id.start_date)
    TextView startDate;
    @BindView(R2.id.ll_start_date)
    LinearLayout llStartDate;
    @BindView(R2.id.end_date)
    TextView endDate;
    @BindView(R2.id.ll_end_date)
    LinearLayout llEndDate;
    Unbinder unbinder;
    private SlimAdapter<TradeListBean> slimAdapter;
    private MVCCoolHelper<List<TradeListBean>> mvcCoolHelper;
    private SparseArray<String> map;
    private TimePickerView startTime;
    private TimePickerView endTime;
    private String startDateTime;  // 起始时间
    private String endDateTime;  // 结束时间


    @Override

    protected int getLayoutId() {
        return R.layout.level_fragment_deal;
    }

    @Override
    public DealFragmentPresenter getPresenter() {
        return new DealFragmentPresenter();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden && mvcCoolHelper != null) {
            mvcCoolHelper.refresh();
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void initView() {
        initPickerView();
        mPresenter.getPingCangType();
        ClickUtil.click(llStartDate, () -> { // 起始时间
            startTime.show();
        });
        ClickUtil.click(llEndDate, () -> {  // 结束时间
            endTime.show();
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        slimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_deal, new SlimInjector<TradeListBean>() {
            @Override
            public void onInject(TradeListBean data, IViewInjector injector, List payloads) {
                injector
                        .textColor(R.id.tv_mm, ContextCompat.getColor(App.INSTANCE, data.getBuyBillType() == 2 ? R.color.levelGreenText : R.color.levelRedText))
                        .text(R.id.tv_mm, data.getBuyBillType() == 2 ? App.INSTANCE.getString(R.string.levelDealFragment0) : App.INSTANCE.getString(R.string.levelDealFragment1))//买入卖出
                        .text(R.id.tv_bz, data.getStockCode())//币种类型
                        .text(R.id.tv_time, data.getCreateTime())//时间
                        .text(R.id.tv_first_left, data.getBillPriceType() == 1 ? App.INSTANCE.getString(R.string.levelDealFragment2) : App.INSTANCE.getString(R.string.levelDealFragment3))//类型
                        .text(R.id.tv_first_right, map == null ? "--" : "类型: " + map.get(data.getSellType()))//平仓类型
                        .text(R.id.tv_second_left, data.getEntrustSuccessLot())//数量
                        .text(R.id.tv_second_right, "浮动盈亏 " + (data.getTradeType() == 1 ? "--" : NumberUtil.keepNoZoreMax4(data.getWinLoseFee()) + ""))//盈亏
                        .text(R.id.tv_third_left, data.getBuyPrice())//建仓价
                        .text(R.id.tv_third_right, data.getSellPrice())//平仓价
                        .text(R.id.tv_four_left, data.getBuyMarginFee())//保证金
                        .text(R.id.tv_four_right, data.getBuyDealFee())//手续费
                        .text(R.id.tv_five_left, data.getStopProfitPrice())//止盈价
                        .text(R.id.tv_five_right, data.getOvernightFee())//过夜费
                        .text(R.id.tv_six_left, data.getStopLossPrice())//止损价
//                        .text(R.id.tv_six_right, data.getStockLever())//杠杆倍数
                ;
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        View dateLayout = View.inflate(getContext(), R.layout.level_date_choose, null);
        RefreshDataSource<TradeListBean> refreshDataSource = new RefreshDataSource<TradeListBean>(coolRefreshView) {
            @Override
            public Flowable<List<TradeListBean>> loadData() {
                if (map == null) {
                    mPresenter.getPingCangType();
                }
                return mPresenter.getTradeList(startDateTime, endDateTime);
            }
        };

        mvcCoolHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcCoolHelper.setDataSource(refreshDataSource);
        mvcCoolHelper.setAdapter(slimAdapter);
        mvcCoolHelper.refresh();
    }


    public void setPingCangType(List<PingCangType> data) {
        map = new SparseArray<>();
        Flowable.fromIterable(data)
                .subscribe(item -> map.put(item.getCode(), item.getName()));
        if (slimAdapter != null) {
            slimAdapter.notifyDataSetChanged();
        }

    }

    public void initPickerView() {
        initDate();
        startTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                startDate.setText(TimeFormatUtil.SF_FORMAT_B.format(date));
                startDateTime = TimeFormatUtil.SF_FORMAT_B.format(date) + " 00:00:00";
                mvcCoolHelper.refresh();
            }
        }).build();
        endTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                endDate.setText(TimeFormatUtil.SF_FORMAT_B.format(date));
                endDateTime = TimeFormatUtil.SF_FORMAT_B.format(date) + " 23:59:59";
                mvcCoolHelper.refresh();
            }
        }).build();
    }

    // 获取当前时间和一个月之前时间
    public void initDate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        endDate.setText(year + "-" + month + "-" + day);
        endDateTime = year + "-" + month + "-" + day + " 23:59:59";
        calendar.add(Calendar.MONTH, -1);    //得到前一个月
        int year1 = calendar.get(Calendar.YEAR);
        int month1 = calendar.get(Calendar.MONTH) + 1;
        int day1 = calendar.get(Calendar.DAY_OF_MONTH);
        startDate.setText(year1 + "-" + month1 + "-" + day1);
        startDateTime = year1 + "-" + month1 + "-" + day1 + " 00:00:00";
    }
}
